package com.suyundeng.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.suyundeng.entity.JsonResult;
import com.suyundeng.entity.SRoleMenu;
import com.suyundeng.system.service.IRoleFunService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;


@Controller
public class RoleFunController {

    @Autowired
    private IRoleFunService roleFunService;

    //给当前角色新添权限
    @ResponseBody
    @PostMapping("/roleFun")
    public JsonResult addFunByRoleId(@RequestParam("roleId") String roleId, @RequestParam("funIdArr") String[] funIdArr){

        try{
            //判断数据库是否含有，获得不含有的数组
            String[] newIdArr = filterId(roleFunService,roleId,funIdArr);
            //给当前角色新添权限
            int data = 0;
            //判断是否为空
            if (newIdArr!=null){
                data = roleFunService.addFunByRoleId(roleId,newIdArr);
            }else {
                data = roleFunService.addFunByRoleId(roleId,funIdArr);
            }
            return new JsonResult(1,"ok",data);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new JsonResult(0,"error",null);
    }

    //删除当前角色取消的权限
    @ResponseBody
    @DeleteMapping("/roleFun")
    public JsonResult deleteFunByRoleId(@RequestParam("roleId") String roleId, @RequestParam("funIdArr") String[] funIdArr){

        try{
            //给当前角色删除权限
            int data = roleFunService.deleteFunByRoleIdAndFunId(roleId,funIdArr);
            return new JsonResult(1,"ok",data);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new JsonResult(0,"error",null);
    }


    public String[] filterId(IRoleFunService service, String roleId,String[] funIdArr){

        List<SRoleMenu> list = service.list(new QueryWrapper<SRoleMenu>().
                eq("role_id",roleId).in("menu_id",funIdArr));
        if (list!=null){
            List<String> idArr = new ArrayList<>();
            boolean flag = false;
            for (String id:funIdArr) {
                for (SRoleMenu r:list) {
                    if (id.equals(r.getMenuId())){
                        flag = true;
                        break;
                    }else {
                        flag = false;
                    }
                }
                if (!flag && !idArr.contains(id)){
                    idArr.add(id);
                }
            }
            return idArr.toArray(new String[idArr.size()]);
        }
        return null;
    }
}
